package 第九周.practice;

import java.io.*;
/**
 * Created by besti on 2018/5/6.
 */
public class FileTest {
    public static void main(String[] args) throws IOException {
        //（1）文件创建（文件类实例化）
        File file = new File("C:\\Users\\besti\\Desktop\\FileTest","HelloWorld.txt");
        //File file = new File("HelloWorld.txt");
//        File file1 = new File("C:\\Users\\besti\\Desktop\\FileTest\\Test\\Test");
//        file1.mkdir();
//        file1.mkdirs();

        if (!file.exists()){
            file.createNewFile();
        }
        // file.delete();
        //（2）文件读写
        //第一种：字节流读写，先写后读
        OutputStream outputStream1 = new FileOutputStream(file);
        byte[] hello = {'H','e','l','l','o',',','W','o','r','l','d','!'};
        outputStream1.write(hello);

        InputStream inputStream1 = new FileInputStream(file);
        while (inputStream1.available()> 0){
            System.out.print((char) inputStream1.read()+"  ");
        }
        inputStream1.close();
        //============================BufferedInputStream====================================
        byte[] buffer = new byte[1024];
        String content = "";
        int flag = 0;
        InputStream inputStream2 = new FileInputStream(file);
        BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStream2);

        while ((flag =bufferedInputStream.read(buffer))!=-1){
            content += new String(buffer,0,flag);
        }

        System.out.println(content);
        bufferedInputStream.close();
//====================================BufferedOutputstream================================================
        OutputStream outputStream2 = new FileOutputStream(file);
        BufferedOutputStream bufferedOutputStream2 = new BufferedOutputStream(outputStream2);
        String content2 = "写入文件的缓冲区内容";
        bufferedOutputStream2.write(content2.getBytes(),0,content2.getBytes().length);
        bufferedOutputStream2.flush();
        bufferedOutputStream2.close();

        //第二种：字符流读写，先写后读(两种读)
        Writer writer2 = new FileWriter(file);
        writer2.write("Hello, I/O Operataion!");
        writer2.flush();
        writer2.append("Hello,World");
        writer2.flush();

        BufferedWriter bufferedWriter = new BufferedWriter(writer2);
        String content3 = "使用bufferedWriter写入";
        bufferedWriter.write(content3,0,content3.length());
        bufferedWriter.flush();
        bufferedWriter.close();

        Reader reader2 = new FileReader(file);
        System.out.println();
        while(reader2.ready()){
            System.out.print((char) reader2.read()+ "  ");
        }
/*
        char[] temp = new char[100];
        reader2.read(temp);
        System.out.println();
        System.out.println(temp);
*/
        BufferedReader bufferedReader = new BufferedReader(reader2);
        while ((content =bufferedReader.readLine())!= null){
            System.out.println(content);
        }
    }
}


